<!doctype html>
<html class="theme-next use-motion theme-next-mist">
<head>
  
<meta charset="UTF-8"/>
<meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1" />
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1"/>

<meta http-equiv="Cache-Control" content="no-transform" />
<meta http-equiv="Cache-Control" content="no-siteapp" />

  <meta name="google-site-verification" content="K8DCBviaoTBKVs28YBB7IBIbospQ9RVlgSh81RYMUhY" />


  <meta name="baidu-site-verification" content="tXr3ZTm3Hx" />



  <link rel="stylesheet" type="text/css" href="/vendors/fancybox/source/jquery.fancybox.css?v=2.1.5"/>


<link rel="stylesheet" type="text/css" href="/css/main.css?v=0.4.5.1"/>

  <meta name="description" content="xgfe's blog. 鲜果前端的技术博客，鲜果前端研发部官方博客。前端基础技术研究：html, html5, javascript, css, css3；前端框架研究：angularJs, react, react native." />


  <meta name="keywords" content="Vue,keep-alive,vue-router," />


  <link rel="alternate" target="_blank" href="/atom.xml" title="xgfe" type="application/atom+xml" />


  <link rel="shorticon icon" type="image/x-icon" href="http://p0.meituan.net/xgfe/2db359f56ce13be30dedef160e0e57ce16958.ico?v=0.4.5.1" />

<meta name="description" content="本文主要对于如何在基于vue的移动端实现滚动位置记录进行了探讨。">
<meta name="keywords" content="Vue,keep-alive,vue-router">
<meta property="og:type" content="article">
<meta property="og:title" content="移动端基于vue-router的滚动位置记录(keep-alive)">
<meta property="og:url" content="http://xgfe.github.io/2018/01/19/lulutia/keep-alive/index.html">
<meta property="og:site_name" content="xgfe">
<meta property="og:description" content="本文主要对于如何在基于vue的移动端实现滚动位置记录进行了探讨。">
<meta property="og:updated_time" content="2018-01-19T03:40:55.000Z">
<meta name="twitter:card" content="summary">
<meta name="twitter:title" content="移动端基于vue-router的滚动位置记录(keep-alive)">
<meta name="twitter:description" content="本文主要对于如何在基于vue的移动端实现滚动位置记录进行了探讨。">


<script type="text/javascript" id="hexo.configuration">
  var CONFIG = {
    scheme: 'Mist',
    sidebar: 'post'
  };
</script>

  <title> 移动端基于vue-router的滚动位置记录(keep-alive) | xgfe </title>
</head>

<body itemscope itemtype="http://schema.org/WebPage" lang="zh-Hans">
  <div style="position: fixed; top: -9999px; left: -9999px;">
    <img src="http://p0.meituan.net/xgfe/082a9624ba5ae8602150a2d43968463e49348.png" alt="xgfe"/>
  </div>
  <!--[if lte IE 8]>
  <div style=' clear: both; height: 59px; padding:0 0 0 15px; position: relative;margin:0 auto;'>
    <a href="http://windows.microsoft.com/en-US/internet-explorer/products/ie/home?ocid=ie6_countdown_bannercode">
      <img src="http://7u2nvr.com1.z0.glb.clouddn.com/picouterie.jpg" border="0" height="42" width="820"
           alt="You are using an outdated browser. For a faster, safer browsing experience, upgrade for free today or use other browser ,like chrome firefox safari."
           style='margin-left:auto;margin-right:auto;display: block;'/>
    </a>
  </div>
<![endif]-->
  

  <script type="text/javascript">
    var _hmt = _hmt || [];
    (function() {
      var hm = document.createElement("script");
      hm.src = "//hm.baidu.com/hm.js?3601d4483819a5ab6ddabb0b6422a328";
      var s = document.getElementsByTagName("script")[0];
      s.parentNode.insertBefore(hm, s);
    })();
  </script>



  <div class="container one-column page-post-detail">
    <div class="headband"></div>

    <header id="header" class="header" itemscope itemtype="http://schema.org/WPHeader">
      <div class="header-inner"><h1 class="site-meta">
  <span class="logo-line-before"><i></i></span>
  <a href="/" class="brand" rel="start">
      <span class="logo">
        <i class="icon-next-logo"></i>
      </span>
      <span class="site-title">xgfe</span>
  </a>
  <span class="logo-line-after"><i></i></span>
</h1>

<div class="site-nav-toggle">
  <button>
    <span class="btn-bar"></span>
    <span class="btn-bar"></span>
    <span class="btn-bar"></span>
  </button>
</div>

<nav class="site-nav">
  
  

  
    <ul id="menu" class="menu menu-left">
      
        
        <li class="menu-item menu-item-home">
          <a href="/" rel="section">
            <i class="menu-item-icon icon-next-home"></i> <br />
            首页
          </a>
        </li>
      
        
        <li class="menu-item menu-item-archives">
          <a href="/archives" rel="section">
            <i class="menu-item-icon icon-next-archives"></i> <br />
            归档
          </a>
        </li>
      
        
        <li class="menu-item menu-item-tags">
          <a href="/tags" rel="section">
            <i class="menu-item-icon icon-next-tags"></i> <br />
            标签
          </a>
        </li>
      
        
        <li class="menu-item menu-item-join">
          <a href="/join" rel="section">
            <i class="menu-item-icon icon-next-join"></i> <br />
            加入我们
          </a>
        </li>
      
      <!-- slide-links added by felix -->
      <li class="menu-item menu-item-slides" style="opacity: 1; transform: translateY(0px);">
        <a href="http://xgfe.github.io/Basics/" target="_blank" rel="section">
          <i class="menu-item-icon icon-next-slides"></i> <br>
          Basics
        </a>
      </li>
      <li class="menu-item menu-item-slides" style="opacity: 1; transform: translateY(0px);">
        <a href="https://slides.com/xgfe" target="_blank" rel="section">
          <i class="menu-item-icon icon-next-slides"></i> <br>
          Slides
        </a>
      </li>

      
      
    </ul>
  

  
    <div class="site-search">
      

    </div>
  

    <div class="site-search">
      <form class="site-search-form" id="gg-form" action="https://www.google.com/webhp" >
        <input type="text" name="q" id="gg-search-input" class="menu-search-input">
      </form>
    </div>
</nav>
 </div>
    </header>

    <main id="main" class="main">
      <div class="main-inner">
        <div id="content" class="content"> 

  <div id="posts" class="posts-expand">
    

  <article class="post post-type-normal " itemscope itemtype="http://schema.org/Article">
    <header class="post-header">

      
      
        <h1 class="post-title" itemprop="name headline">
          
          
            
              移动端基于vue-router的滚动位置记录(keep-alive)
            
          
        </h1>
      

      <div class="post-meta">
        <span class="post-time">
          发表于
          <time itemprop="dateCreated" datetime="2018-01-19T10:57:00+08:00" content="2018-01-19">
            2018-01-19
          </time>
        </span>

        
          <span class="post-category" >
            &nbsp; | &nbsp; 作者
            
              <span itemprop="about" itemscope itemtype="https://schema.org/Thing">
                <a href="/categories/lulutia/" itemprop="url" rel="index">
                  <span itemprop="name">lulutia</span>
                </a>
              </span>

              
              

            
          </span>
        

        
          
        

        <!-- tags 挪动位置 -->
        
          <span class="post-tags">
            &nbsp; | &nbsp;
            
              <a href="/tags/Vue/" rel="tag"><i class="icon-next-tags"></i>Vue</a>
            
              <a href="/tags/keep-alive/" rel="tag"><i class="icon-next-tags"></i>keep-alive</a>
            
              <a href="/tags/vue-router/" rel="tag"><i class="icon-next-tags"></i>vue-router</a>
            
          </span>
        
      </div>
    </header>

    <div class="post-body">

      
      

      
        <span itemprop="articleBody"><p>本文主要对于如何在基于vue的移动端实现滚动位置记录进行了探讨。</p>
<a id="more"></a>
<p>在日常开发中，我们经常的会遇见与滚动位置记录相关的需求。多见于从列表页进入详情页，然后进行回退。对这种情况提炼出一套解决方案是相当有必要的。</p>
<h4 id="背景"><a href="#背景" class="headerlink" title="背景"></a>背景</h4><p>在日常开发中，我们经常的会遇见与滚动位置记录相关的需求。多见于从列表页进入详情页，然后进行回退。原因如下：</p>
<ul>
<li>在移动开发中，列表多是由无限滚动进行加载的，因此如果回退后又从头进行加载实际上用户体验是相当不好的</li>
<li>如果列表页的展现对实时性要求不高甚至长期不变，则回退后又进行的重新加载实际上是性能的浪费<br>针对上面，在实际操作时更理想的情况是，对于实时性不高的列表，从列表页进入详情页又回退后，列表页会保存之前的位置。<br>在基于vue-router的项目中，为了实现上述效果可以使用其提供的keep-alive功能与scrollBehavior进行配合。</li>
</ul>
<h4 id="keep-alive与scrollBehavior"><a href="#keep-alive与scrollBehavior" class="headerlink" title="keep-alive与scrollBehavior"></a>keep-alive与scrollBehavior</h4><ul>
<li>keep-alive: keep-alive是Vue内置的一个抽象组件，它自身不会渲染DOM元素也不会出现在父组件链中，它只是在包裹动态组件时会缓存不活动的组件实例，而不是销毁它们。<a href="https://cn.vuejs.org/v2/api/#keep-alive" target="_blank" rel="external">更多使用方法详见Vue官方文档</a>。</li>
<li>scrollBehavior: scrollBehavior是由vue-router中Router实例提供的方法，它接受三个参数，分别为(to, from, savedPosition)，其中to和from是路由对象，而savedPosition是当 popstate导航(通过浏览器的 前进/后退 按钮触发)时记录的位置信息。<ul>
<li>scrollBehavior返回滚动位置的对象信息，如{ x: number, y: number}，如果返回的是<a href="https://developer.mozilla.org/zh-CN/docs/Glossary/Falsy" target="_blank" rel="external">falsy</a>或者空对象则不会发生滚动。</li>
<li>注意scrollBehavior只在HTML5 history模式下可用。</li>
</ul>
</li>
</ul>
<h4 id="实际使用"><a href="#实际使用" class="headerlink" title="实际使用"></a>实际使用</h4><ul>
<li>使用router-view配合keep-alive: 在入口文件通过v-if进行对特定页面的缓存。</li>
</ul>
<figure class="highlight js"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div><div class="line">5</div><div class="line">6</div></pre></td><td class="code"><pre><div class="line">&lt;div <span class="class"><span class="keyword">class</span></span>=<span class="string">"page-group"</span>&gt;</div><div class="line">  &lt;keep-alive&gt;</div><div class="line">    &lt;router-view class="view" v-if="$route.meta.keep_alive"&gt;&lt;/router-view&gt;</div><div class="line">  &lt;/keep-alive&gt;</div><div class="line">  &lt;router-view class="view" v-if="!$route.meta.keep_alive"&gt;&lt;/router-view&gt;</div><div class="line">&lt;/div&gt;</div></pre></td></tr></table></figure>
<ul>
<li>对路由进行配置，开启HTML5 history模式并配置scrollBehavior：</li>
</ul>
<figure class="highlight js"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div><div class="line">5</div></pre></td><td class="code"><pre><div class="line"><span class="keyword">const</span> router = <span class="keyword">new</span> VueRouter(&#123;</div><div class="line">		<span class="attr">mode</span>: <span class="string">'history'</span>,</div><div class="line">		<span class="attr">scrollBehavior</span>: scrollBehavior,</div><div class="line">		routes</div><div class="line">&#125;);</div></pre></td></tr></table></figure>
<ul>
<li><p>对路由进行配置，定制scrollBehavior方法，在这里会遇见以下几个问题：        </p>
<ul>
<li><p>如何判断页面是否需要保留位置信息: </p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div><div class="line">5</div><div class="line">6</div><div class="line">7</div><div class="line">8</div><div class="line">9</div><div class="line">10</div><div class="line">11</div><div class="line">12</div></pre></td><td class="code"><pre><div class="line"><span class="keyword">export</span> <span class="keyword">default</span> &#123;</div><div class="line">  <span class="attr">name</span>: constants.NAME,</div><div class="line">  <span class="attr">path</span>: constants.PATH,</div><div class="line">  <span class="attr">component</span>: <span class="built_in">module</span>,</div><div class="line">  <span class="attr">meta</span>: &#123;</div><div class="line">    <span class="attr">title</span>: constants.TITLE,</div><div class="line">    <span class="attr">val_cid</span>: constants.VAL_CID,</div><div class="line">    <span class="attr">requireAuth</span>: constants.REQUIRE_AUTH,</div><div class="line">    <span class="attr">keep_alive</span>: <span class="literal">true</span></div><div class="line">  &#125;,</div><div class="line">  constants</div><div class="line">&#125;;</div></pre></td></tr></table></figure>
<p>我们通过在路由上添加了一个参数keep_alive来声明当前路由是否要启动keep_alive的功能。</p>
</li>
<li><p>如何根据需要刷新页面，重新获取数据: 假如我们有三个页面，通过A进入B，通过B进入C。那么其中通过A进入B是需要进行数据刷新的；而从B进入C，再从C返回B则不需要进行数据刷新。因此针对同一个页面我们需要使用一种机制来判断多久需要数据刷新。<br>基本我们可以提炼出：通过<strong>跳转</strong>的是需要进行数据刷新的；而通过默认浏览器行为的是不需要进行浏览器刷新的。<br>看vue-router的源码中我们会发现下面的代码：</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div><div class="line">5</div><div class="line">6</div><div class="line">7</div><div class="line">8</div></pre></td><td class="code"><pre><div class="line"><span class="built_in">window</span>.addEventListener(<span class="string">'popstate'</span>, e =&gt; &#123;</div><div class="line">	.......</div><div class="line">    	this.transitionTo(location, route =&gt; &#123;</div><div class="line">      <span class="keyword">if</span> (supportsScroll) &#123;</div><div class="line">        handleScroll(router, route, current, <span class="literal">true</span>)</div><div class="line">      &#125;</div><div class="line">    &#125;)</div><div class="line">  &#125;)</div></pre></td></tr></table></figure>
<figure class="highlight js"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div><div class="line">5</div><div class="line">6</div><div class="line">7</div><div class="line">8</div></pre></td><td class="code"><pre><div class="line">push (location: RawLocation, onComplete?: <span class="built_in">Function</span>, onAbort?: <span class="built_in">Function</span>) &#123;</div><div class="line">  ...</div><div class="line">  this.transitionTo(location, route =&gt; &#123;</div><div class="line">    ...</div><div class="line">    handleScroll(<span class="keyword">this</span>.router, route, fromRoute, <span class="literal">false</span>)</div><div class="line">    ...</div><div class="line">  &#125;, onAbort)</div><div class="line">&#125;</div></pre></td></tr></table></figure>
<p>上面代码在处理popstate时调用的handleScroll方法传入的最后一个参数是true，但是自己重写的push、replace等函数调用handleScroll时传入的最后一个参数都是false。<br>而在scroll.js中，我们可以看到handleScroll函数的最后一个参数就是用来区分浏览器默认行为，和router-link的行为的。</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div><div class="line">5</div><div class="line">6</div><div class="line">7</div><div class="line">8</div><div class="line">9</div></pre></td><td class="code"><pre><div class="line">......</div><div class="line">const behavior = router.options.scrollBehavior</div><div class="line">......</div><div class="line">router.app.$nextTick(<span class="function"><span class="params">()</span> =&gt;</span> &#123;</div><div class="line">   <span class="keyword">const</span> position = getScrollPosition()</div><div class="line">   <span class="keyword">const</span> shouldScroll = behavior.call(router, to, <span class="keyword">from</span>, isPop ? position : <span class="literal">null</span>)</div><div class="line">......</div><div class="line">  &#125;)</div><div class="line">&#125;</div></pre></td></tr></table></figure>
<p>在上面一段代码中，我们可以看到，对于浏览器默认行为，调用自定义的scrollBehavior函数后传参的savedPosition为保存的position，对于跳转这种则传参的savedPosition为null。<br><strong>通过上面，我们已经能区分什么时候需要进行数据刷新了</strong>。之后，我们需要修改两部分的代码，一部分是scrollBehavior，修改它来根据不同的情况返回不同的滚动值；另外一部分是实际keep-alive的页面的渲染逻辑，它需要根据不同的情况来选择是否进行数据获取。</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div><div class="line">5</div><div class="line">6</div><div class="line">7</div></pre></td><td class="code"><pre><div class="line"><span class="keyword">const</span> scrollBehavior = <span class="function">(<span class="params">to, <span class="keyword">from</span>, savedPosition</span>) =&gt;</span> &#123;</div><div class="line">  <span class="keyword">if</span> (to.matched.some(<span class="function"><span class="params">t</span> =&gt;</span> t.meta.keep_alive)) &#123;</div><div class="line">  	to.meta.saved_position = savedPosition; <span class="comment">// 传递这个值到具体页面来判断是否进行数据刷新</span></div><div class="line">    <span class="keyword">let</span> back = savedPosition ? savedPosition : &#123;<span class="attr">x</span>: <span class="number">0</span>, <span class="attr">y</span>: <span class="number">0</span>&#125;;</div><div class="line">    <span class="keyword">return</span> back;</div><div class="line">  &#125;</div><div class="line">&#125;;</div></pre></td></tr></table></figure>
<figure class="highlight js"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div><div class="line">5</div><div class="line">6</div><div class="line">7</div><div class="line">8</div></pre></td><td class="code"><pre><div class="line">beforeRouteEnter: <span class="function"><span class="keyword">function</span>(<span class="params">to ,from, next</span>)</span>&#123;</div><div class="line">     next(<span class="function"><span class="params">vm</span> =&gt;</span> &#123;</div><div class="line">     	<span class="comment">// 通过对null的判断决定是否进行数据刷新</span></div><div class="line">       <span class="keyword">if</span> (to.meta.saved_position === <span class="literal">null</span>) &#123;</div><div class="line">         vm.initAll();</div><div class="line">       &#125;</div><div class="line">     &#125;)</div><div class="line">   &#125;</div></pre></td></tr></table></figure>
<p>这里需要注意必须要在beforeRouteEnter的next里面进行调用，因为一般的生命周期钩子比如mounted等都会被keep-alive给吃掉。</p>
</li>
</ul>
</li>
</ul>
<h4 id="需要注意的点"><a href="#需要注意的点" class="headerlink" title="需要注意的点"></a>需要注意的点</h4><p>在实际使用中，其实上面这种做法会有问题。我们会发现，在A页面进行刷新，然后第一次从A进入B，又从B返回A的时候，并没有滚动到特定的位置。它滚动到了顶部。通过代码调试，我们可以看到，这一次返回的savedPosition为undefined，因此在判断back的时候会赋值{x: 0, y: 0}。</p>
<p>为了解决这个问题，我们需要手动记录一下滚动的位置。</p>
<p>在路由跳转的时候，如果from的是keep-alive的页面，则记录它的位置，并保存在路由上。之后通过浏览器行为进入这个页面的时候对位置进行判定，如果有就取这个值。</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div><div class="line">5</div><div class="line">6</div><div class="line">7</div><div class="line">8</div><div class="line">9</div><div class="line">10</div><div class="line">11</div></pre></td><td class="code"><pre><div class="line"><span class="keyword">const</span> scrollBehavior = <span class="function">(<span class="params">to, <span class="keyword">from</span>, savedPosition</span>) =&gt;</span> &#123;</div><div class="line">  <span class="keyword">if</span> (to.matched.some(<span class="function"><span class="params">t</span> =&gt;</span> t.meta.keep_alive)) &#123;</div><div class="line">    <span class="keyword">if</span> (savedPosition === <span class="literal">null</span>) &#123;</div><div class="line">      to.meta.saved_position = <span class="literal">null</span>;</div><div class="line">    &#125; <span class="keyword">else</span> &#123;</div><div class="line">      savedPosition = to.meta.saved_position;</div><div class="line">    &#125;</div><div class="line">    <span class="keyword">let</span> back = savedPosition ? savedPosition : &#123;<span class="attr">x</span>: <span class="number">0</span>, <span class="attr">y</span>: <span class="number">0</span>&#125;;</div><div class="line">    <span class="keyword">return</span> back;</div><div class="line">  &#125;</div><div class="line">&#125;;</div></pre></td></tr></table></figure>
<figure class="highlight js"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div><div class="line">5</div><div class="line">6</div><div class="line">7</div></pre></td><td class="code"><pre><div class="line">router.beforeEach(<span class="function">(<span class="params">to, <span class="keyword">from</span>, next</span>) =&gt;</span> &#123;</div><div class="line">	...</div><div class="line">	if (<span class="keyword">from</span>.meta.keep_alive) &#123;</div><div class="line">    <span class="keyword">from</span>.meta.saved_position = &#123;<span class="attr">x</span>: <span class="built_in">window</span>.pageXOffset, <span class="attr">y</span>: <span class="built_in">window</span>.pageXOffset&#125;;</div><div class="line">  &#125;</div><div class="line">  ...</div><div class="line">&#125;)</div></pre></td></tr></table></figure>
<p>自此，可以解决这个问题。<br>那么我们接下来看下，为啥会出现undefined。在vue-router的代码中，有下面几段：</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div><div class="line">5</div><div class="line">6</div><div class="line">7</div><div class="line">8</div><div class="line">9</div><div class="line">10</div><div class="line">11</div><div class="line">12</div></pre></td><td class="code"><pre><div class="line"> router.app.$nextTick(<span class="function"><span class="params">()</span> =&gt;</span> &#123;</div><div class="line">   <span class="keyword">const</span> position = getScrollPosition()</div><div class="line">   <span class="keyword">const</span> shouldScroll = behavior.call(router, to, <span class="keyword">from</span>, isPop ? position : <span class="literal">null</span>)</div><div class="line">......</div><div class="line"> &#125;)</div><div class="line"> </div><div class="line"> <span class="function"><span class="keyword">function</span> <span class="title">getScrollPosition</span> (<span class="params"></span>): ?<span class="title">Object</span> </span>&#123;</div><div class="line">  <span class="keyword">const</span> key = getStateKey()</div><div class="line">  <span class="keyword">if</span> (key) &#123;</div><div class="line">    <span class="keyword">return</span> positionStore[key]</div><div class="line">  &#125;</div><div class="line">&#125;</div></pre></td></tr></table></figure>
<p>我们可以看到，如果在调用getScrollPosition方法时，如果在positionStore里面没有找到对应当前key的数据，则会返回undefined。</p>
<p>那么为什么会没找到当前的key呢，因为刷新后，也就是当router进行初始化时，当前的路由状态并没有在history上进行注册，即window.history.state为null。此时，当在当前页面A进行滑动后跳转到其他页面B时，会将位置信息存储到positionStore上面，key为初始化的window.performance.now().toFixed(3)。此时，点击回退按钮，会触发popstate来获取A的信息。但是因为A的history state并没有注册。所以无法找到匹配的位置信息。</p>
<p>不过好的是现在这个问题已经被修复了，在<a href="https://github.com/vuejs/vue-router/releases/tag/v2.8.0" target="_blank" rel="external">2.8.0及其以上版本</a>中可以看到。修复思路就是在路由进行初始化的时候调用window.history.replaceState({ key: getStateKey() }, ‘’)来进行一个注册。具体见<a href="https://github.com/vuejs/vue-router/issues/1585" target="_blank" rel="external">链接</a></p>
<h4 id="参考"><a href="#参考" class="headerlink" title="参考"></a>参考</h4><ul>
<li><a href="https://www.jianshu.com/p/fe238d8e7c6d" target="_blank" rel="external">vue-router 中使用 keep-alive 控制 ajax 请求的缓存策略(二)</a></li>
<li><a href="https://github.com/vuejs/vue-router/blob/dev/src/util/scroll.js" target="_blank" rel="external">vue-router dev分支源码</a></li>
<li><a href="https://github.com/vuejs/vue-router/issues/772" target="_blank" rel="external">scrollBehavior doesn’t store a scrolling position on the first page #772</a></li>
<li><a href="https://github.com/vuejs/vue-router/issues/1585" target="_blank" rel="external">scrollBehavior doesn’t work for initial route in Firefox #1585</a></li>
</ul>
</span>
      
    </div>

    <footer class="post-footer">

      
        <div class="post-nav">
          <div class="post-nav-prev post-nav-item">
            
              <a href="/2018/01/22/liuhaifeng/Regular-Expression/" rel="prev">正则表达式总结</a>
            
          </div>

          <div class="post-nav-next post-nav-item">
            
              <a href="/2018/01/05/hardhpp/node_crawler/" rel="next">Node学习系列(1) -- Node实现爬虫</a>
            
          </div>
        </div>
      

      
      
    </footer>
  </article>



    <div class="post-spread">
      
        <!-- JiaThis Button BEGIN -->
<div class="jiathis_style">
  <a class="jiathis_button_tsina"></a>
  <a class="jiathis_button_tqq"></a>
  <a class="jiathis_button_weixin"></a>
  <a class="jiathis_button_cqq"></a>
  <a class="jiathis_button_douban"></a>
  <a class="jiathis_button_renren"></a>
  <a class="jiathis_button_qzone"></a>
  <a class="jiathis_button_kaixin001"></a>
  <a class="jiathis_button_copy"></a>
  <a href="http://www.jiathis.com/share" class="jiathis jiathis_txt jiathis_separator jtico jtico_jiathis" target="_blank"></a>
  <a class="jiathis_counter_style"></a>
</div>
<script type="text/javascript" >
  var jiathis_config={
    hideMore:false
  }
</script>
<script type="text/javascript" src="http://v3.jiathis.com/code/jia.js" charset="utf-8"></script>
<!-- JiaThis Button END -->

      
    </div>
  </div>

 </div>

        

        
          <div class="comments" id="comments">
            <div id="SOHUCS" sid="" ></div>
          </div>
        
      </div>

      
  
  <div class="sidebar-toggle">
    <div class="sidebar-toggle-line-wrap">
      <span class="sidebar-toggle-line sidebar-toggle-line-first"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-middle"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-last"></span>
    </div>
  </div>

  <aside id="sidebar" class="sidebar">
    <div class="sidebar-inner">

      
        <ul class="sidebar-nav motion-element">
          <li class="sidebar-nav-toc sidebar-nav-active" data-target="post-toc-wrap" >
            文章目录
          </li>
          <li class="sidebar-nav-overview" data-target="site-overview">
            站点概览
          </li>
        </ul>
      

      <section class="site-overview">
        <div class="site-author motion-element" itemprop="author" itemscope itemtype="http://schema.org/Person">
          <a href="https://github.com/xgfe" target="_blank"><img class="site-author-image" src="http://p0.meituan.net/xgfe/082a9624ba5ae8602150a2d43968463e49348.png" alt="xgfe" itemprop="image"/></a>
          <p class="site-author-name" itemprop="name">xgfe</p>
        </div>
        <p class="site-description motion-element" itemprop="description">xgfe's blog. 鲜果前端的技术博客，鲜果前端研发部官方博客。前端基础技术研究：html, html5, javascript, css, css3；前端框架研究：angularJs, react, react native.</p>
        <nav class="site-state motion-element">
          <div class="site-state-item site-state-posts">
            <a href="/archives">
              <span class="site-state-item-count">89</span>
              <span class="site-state-item-name">日志</span>
            </a>
          </div>

          <div class="site-state-item site-state-categories">
            
              <span class="site-state-item-count">37</span>
              <span class="site-state-item-name">作者</span>
              
          </div>

          <div class="site-state-item site-state-tags">
            <a href="/tags">
              <span class="site-state-item-count">131</span>
              <span class="site-state-item-name">标签</span>
              </a>
          </div>

        </nav>

        
          <div class="feed-link motion-element">
            <a href="/atom.xml" target="_blank" rel="alternate">
              <i class="menu-item-icon icon-next-feed"></i>
              RSS
            </a>
          </div>
        

        <div class="links-of-author motion-element">
          
            
              <span class="links-of-author-item">
                <a href="https://github.com/xgfe" target="_blank">GitHub</a>
              </span>
            
          
        </div>

        
        

        <div class="links-of-author motion-element">
          
        </div>

      </section>

      
        <section class="post-toc-wrap sidebar-panel-active">
          <div class="post-toc-indicator-top post-toc-indicator"></div>
          <div class="post-toc">
            
            
              <div class="post-toc-content"><ol class="nav"><li class="nav-item nav-level-4"><a class="nav-link" href="#背景"><span class="nav-number">1.</span> <span class="nav-text">背景</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#keep-alive与scrollBehavior"><span class="nav-number">2.</span> <span class="nav-text">keep-alive与scrollBehavior</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#实际使用"><span class="nav-number">3.</span> <span class="nav-text">实际使用</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#需要注意的点"><span class="nav-number">4.</span> <span class="nav-text">需要注意的点</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#参考"><span class="nav-number">5.</span> <span class="nav-text">参考</span></a></li></ol></div>
            
          </div>
          <div class="post-toc-indicator-bottom post-toc-indicator"></div>
        </section>
      

    </div>
  </aside>


    </main>

    <footer id="footer" class="footer">
      <div class="footer-inner"> <div class="copyright" >
  
  &copy; &nbsp; 
  <span itemprop="copyrightYear">2018</span>
  <span class="with-love">
    <i class="icon-next-heart"></i>
  </span>
  <span class="author" itemprop="copyrightHolder">xgfe</span>
</div>

<div class="powered-by">
  由 <a class="theme-link" target="_blank" href="http://hexo.io">Hexo</a> 强力驱动
</div>

<div class="theme-info">
  主题 -
  <a class="theme-link" target="_blank" href="https://github.com/iissnan/hexo-theme-next">
    NexT.Mist
  </a>
</div>


 </div>
    </footer>

    <div class="back-to-top"></div>
  </div>

  <script type="text/javascript" src="/vendors/jquery/index.js?v=2.1.3"></script>

  
  
  
    <script type="text/javascript"> 
(function(){ 
var appid = 'cysWiXvkm'; 
var conf = 'prod_fc970dbe85103c7a79b2c4f3dc7fb190'; 
var width = window.innerWidth || document.documentElement.clientWidth; 
if (width < 960) { 
window.document.write('<script id="changyan_mobile_js" charset="utf-8" type="text/javascript" src="http://changyan.sohu.com/upload/mobile/wap-js/changyan_mobile.js?client_id=' + appid + '&conf=' + conf + '"><\/script>'); } else { var loadJs=function(d,a){var c=document.getElementsByTagName("head")[0]||document.head||document.documentElement;var b=document.createElement("script");b.setAttribute("type","text/javascript");b.setAttribute("charset","UTF-8");b.setAttribute("src",d);if(typeof a==="function"){if(window.attachEvent){b.onreadystatechange=function(){var e=b.readyState;if(e==="loaded"||e==="complete"){b.onreadystatechange=null;a()}}}else{b.onload=a}}c.appendChild(b)};loadJs("http://changyan.sohu.com/upload/changyan.js",function(){window.changyan.api.config({appid:appid,conf:conf})}); } })(); </script>
    

  


  
  
  <script type="text/javascript" src="/vendors/fancybox/source/jquery.fancybox.pack.js"></script>
  <script type="text/javascript" src="/js/fancy-box.js?v=0.4.5.1"></script>


  <script type="text/javascript" src="/js/helpers.js?v=0.4.5.1"></script>
  

  <script type="text/javascript" src="/vendors/velocity/velocity.min.js"></script>
  <script type="text/javascript" src="/vendors/velocity/velocity.ui.min.js"></script>

  <script type="text/javascript" src="/js/motion_global.js?v=0.4.5.1" id="motion.global"></script>




  <script type="text/javascript" src="/js/nav-toggle.js?v=0.4.5.1"></script>
  <script type="text/javascript" src="/vendors/fastclick/lib/fastclick.min.js?v=1.0.6"></script>

  
  
<script type="text/javascript" src="/js/bootstrap.scrollspy.js?v=0.4.5.1" id="bootstrap.scrollspy.custom"></script>


<script type="text/javascript" id="sidebar.toc.highlight">
  $(document).ready(function () {
    var tocSelector = '.post-toc';
    var $tocSelector = $(tocSelector);
    var activeCurrentSelector = '.active-current';

    $tocSelector
      .on('activate.bs.scrollspy', function () {
        var $currentActiveElement = $(tocSelector + ' .active').last();

        removeCurrentActiveClass();
        $currentActiveElement.addClass('active-current');

        $tocSelector[0].scrollTop = $currentActiveElement.position().top;
      })
      .on('clear.bs.scrollspy', function () {
        removeCurrentActiveClass();
      });

    function removeCurrentActiveClass () {
      $(tocSelector + ' ' + activeCurrentSelector)
        .removeClass(activeCurrentSelector.substring(1));
    }

    function processTOC () {
      getTOCMaxHeight();
      toggleTOCOverflowIndicators();
    }

    function getTOCMaxHeight () {
      var height = $('.sidebar').height() -
                   $tocSelector.position().top -
                   $('.post-toc-indicator-bottom').height();

      $tocSelector.css('height', height);

      return height;
    }

    function toggleTOCOverflowIndicators () {
      tocOverflowIndicator(
        '.post-toc-indicator-top',
        $tocSelector.scrollTop() > 0 ? 'show' : 'hide'
      );

      tocOverflowIndicator(
        '.post-toc-indicator-bottom',
        $tocSelector.scrollTop() >= $tocSelector.find('ol').height() - $tocSelector.height() ? 'hide' : 'show'
      )
    }

    $(document).on('sidebar.motion.complete', function () {
      processTOC();
    });

    $('body').scrollspy({ target: tocSelector });
    $(window).on('resize', function () {
      if ( $('.sidebar').hasClass('sidebar-active') ) {
        processTOC();
      }
    });

    onScroll($tocSelector);

    function onScroll (element) {
      element.on('mousewheel DOMMouseScroll', function (event) {
          var oe = event.originalEvent;
          var delta = oe.wheelDelta || -oe.detail;

          this.scrollTop += ( delta < 0 ? 1 : -1 ) * 30;
          event.preventDefault();

          toggleTOCOverflowIndicators();
      });
    }

    function tocOverflowIndicator (indicator, action) {
      var $indicator = $(indicator);
      var opacity = action === 'show' ? 0.4 : 0;
      $indicator.velocity ?
        $indicator.velocity('stop').velocity({
          opacity: opacity
        }, { duration: 100 }) :
        $indicator.stop().animate({
          opacity: opacity
        }, 100);
    }

  });
</script>

<script type="text/javascript" id="sidebar.nav">
  $(document).ready(function () {
    var html = $('html');
    var TAB_ANIMATE_DURATION = 200;
    var hasVelocity = $.isFunction(html.velocity);

    $('.sidebar-nav li').on('click', function () {
      var item = $(this);
      var activeTabClassName = 'sidebar-nav-active';
      var activePanelClassName = 'sidebar-panel-active';
      if (item.hasClass(activeTabClassName)) {
        return;
      }

      var currentTarget = $('.' + activePanelClassName);
      var target = $('.' + item.data('target'));

      hasVelocity ?
        currentTarget.velocity('transition.slideUpOut', TAB_ANIMATE_DURATION, function () {
          target
            .velocity('stop')
            .velocity('transition.slideDownIn', TAB_ANIMATE_DURATION)
            .addClass(activePanelClassName);
        }) :
        currentTarget.animate({ opacity: 0 }, TAB_ANIMATE_DURATION, function () {
          currentTarget.hide();
          target
            .stop()
            .css({'opacity': 0, 'display': 'block'})
            .animate({ opacity: 1 }, TAB_ANIMATE_DURATION, function () {
              currentTarget.removeClass(activePanelClassName);
              target.addClass(activePanelClassName);
            });
        });

      item.siblings().removeClass(activeTabClassName);
      item.addClass(activeTabClassName);
    });

    $('.post-toc a').on('click', function (e) {
      e.preventDefault();
      var targetSelector = escapeSelector(this.getAttribute('href'));
      var offset = $(targetSelector).offset().top;
      hasVelocity ?
        html.velocity('stop').velocity('scroll', {
          offset: offset  + 'px',
          mobileHA: false
        }) :
        $('html, body').stop().animate({
          scrollTop: offset
        }, 500);
    });

    // Expand sidebar on post detail page by default, when post has a toc.
    var $tocContent = $('.post-toc-content');
    if (isDesktop() && CONFIG.sidebar === 'post') {
      if ($tocContent.length > 0 && $tocContent.html().trim().length > 0) {
        displaySidebar();
      }
    }
  });
</script>



  <script type="text/javascript">
    $(document).ready(function () {
      if (CONFIG.sidebar === 'always') {
        displaySidebar();
      }
      if (isMobile()) {
        FastClick.attach(document.body);
      }
    });
  </script>

  

  
  

  
  <script type="text/javascript" src="/js/lazyload.js"></script>
  <script type="text/javascript">
    $(function () {
      $("#posts").find('img').lazyload({
        placeholder: "/images/loading.gif",
        effect: "fadeIn"
      });
    });
  </script>

  <!-- google search, added by felix -->
  <script>
      $('#gg-form').on('submit', function(e) {
        var keyword = $.trim($(this).find('#gg-search-input').val());
        if (keyword) {
          location.href = 'https://www.google.com.hk/?gfe_rd=cr&ei=hXw8VpjtHuLC8AeSuIjQAg&gws_rd=ssl#safe=strict&q='+encodeURIComponent(keyword)+'+site:xgfe.github.io';
        }
        return false;
      });
  </script>
  <!-- baidu 站长自动推送 -->
  <script>
  (function(){
      var bp = document.createElement('script');
      bp.src = '//push.zhanzhang.baidu.com/push.js';
      var s = document.getElementsByTagName("script")[0];
      s.parentNode.insertBefore(bp, s);
  })();
  </script>
</body>
</html>
